<?php
/*
 * [recordform id='RecordForm']
 *
 */

namespace WebApper\Shortcode;

class RecordForm extends \WebApper\Shortcode {
	
    /**
     * Define shortcode properties
     *
     */
	protected $shortcode = 'recordform';
	protected $defaults = array(
		'id' => null,					// The unique ID to use for the shortcode. Default: none. Required.
		'usercap' => 'logged_out',		// The minimum user capability required to access the Form. OPTIONS: 'logged_out', 'read', 'edit_posts', 'edit_others_posts', 'edit_users', 'edit_pages', 'edit_plugins'. Default 'logged_out'.
		'posttype' => null,				// The cutom post type (ID) to display. Default: none. Required.
		'fieldset' => null,				// The set of fields to include in the indextable. Default: none. Required if 'include' is not specified. You may use one or both.
		'include' => null,				// field-id's of individual fields to include in the indextable. Default: none. Required if 'fieldset' is not specified. You may use one or both.
		'exclude' => null,				// field-id's of individual fields to exclude in the indextable. Default: none
		'titlefield' => null,			// The field to use for the post title. Default: none. Required.
		'view' => 'SideBySide',			// The styles used to display the form. OPTIONS: 'SideBySide', 'Vertical', 'Inline', 'Search', 'Modal'. Default: 'SideBySide'.
		'placeholders' => 'false',		// Whether to use field labels as placeholders. OPTIONS: true, false.
		'submitlabel' => 'Submit',		// The label to use for the submit button. Default: 'Submit'.
		'successsave' => 'Submission successful!',		// The message to display upon successful save.
		'failuresave' => 'Submission unsuccessful.',	// The message to display upon unsuccessful save.
		'ajax' => 'false',				// Whether to submit the form via ajax. OPTIONS: true, false.
		'modalbtn' => null,				// The label to use for the trigger modal button. Default: none. Required if 'view=Modal'.
		'modalheading' => null,			// The heading to use for the modal. Default: none. Required if 'view=Modal'.
		'novalidate' => 'false',		// Whether to add a 'novalidate' attribute to the form. OPTIONS: true, false. Default: false.
	);

    /**
     * Handles the add post shortcode
     *
     * @param array $atts
     */
    public function shortcode( $atts ) {

		// Get shortcode attributes
			extract( shortcode_atts( $this->defaults, $atts ) );
			
		// Add Filter to allow hooking before rendering
			$atts = apply_filters( 'recordform_pre_render', $atts );

		// Check for required shortcode attributes
			$msg = $this->has_req_attrs( $atts );
			if ( $msg !== true )
				return $msg;

        // Check if current user has proper privileges
			if ( !$this->user_has_cap( $usercap ) )
				return;

		// Process form $_POST's
			if ( isset( $_POST['web_apper_form'] ) ) :
				if ( \PFBC\Form::isValid($_POST['web_apper_form']) ) :
					// The form's submitted data has been validated. Proceed with further processing.
					$this->add_record();
				endif;
			endif;

		// Get the fields
			$this->get_fields( $atts, true );

		// Configure form settings
			$this->config_form( $atts );  // Check if user has proper privileges

		// Build the form
			$form = new \PFBC\Form($id);
			$form->configure( $this->formConfig );
			$form->addElement(new \PFBC\Element\Hidden('web_apper_form', $id));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_nonce', wp_create_nonce( 'WebApperAwesomeness!87' )));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_task', 'add'));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_posttype', $posttype));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_titlefield', $titlefield));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_success_save', $successsave));
			$form->addElement(new \PFBC\Element\Hidden('web_apper_failure_save', $failuresave));
			if ( $ajax == 'true' || $view == 'Modal' )
				$form->addElement(new \PFBC\Element\Hidden('action', 'web_apper' . $this->shortcode));
			if ( $view == 'Modal' ) :
				$form->addElement(new \PFBC\Element\ModalToggle($modalbtn));
				$form->addElement(new \PFBC\Element\ModalHeading($modalheading));
			endif;
			foreach ( $this->fields as $field ) :
				$this->add_form_field( $field, $form );
			endforeach;
			$form->addElement(new \PFBC\Element\Button($submitlabel));
            $form->render();  // Output the form

		// Add ajax script to footer
			if ( $ajax == 'true' || $view == 'Modal' ) :
				?>
				<script type="text/javascript">
					jQuery("form#<?php echo $id; ?>").bind('submit', function() {
						jQuery('.alert').alert('close');  // Close any alerts that may be open
					});
					function parseResponse<?php echo $id; ?>(response) {
						var result = jQuery.parseJSON(response);  // Parse response
						//alert(response);
						jQuery("form#<?php echo $id; if ( $view == 'Modal' ) echo ' .modal-body'; ?>").prepend(result.htmlalert);  // Insert into Modal
					}
				</script>
				<?php
			endif;

	}

    /**
     * Checks if a shortcode has required attributes
     *
     * @param array $atts
     * @since 1.0
     */
	protected function has_req_attrs( $atts ) {

		// Check for required shortcode attributes
			if ( $atts['id'] == null )
				return 'You must give the form a unique ID, i.e., [form id=\'form-1\']';
			if ( $atts['posttype'] == null )
				return 'You must specify a post type for the form, i.e., [form posttype=\'lead-pt\']';
			if ( $atts['fieldset'] == null && $atts['include'] == null )
				return 'You must specify the \'fieldset\' or \'include\' attribute so you have some fields the form, i.e., [form fieldset=\'group_1\']';
			if ( $atts['titlefield'] == null )
				return 'You must specify a field to use for the post title, i.e., [form titlefield=\'field-id]\'';
			if ( $atts['view'] == 'Modal' && $atts['modalbtn'] == null )
				return 'You must specify the label to use for the trigger modal button, i.e., [form modalbtn=\'Apply Now\']';
			if ( $atts['view'] == 'Modal' && $atts['modalheading'] == null )
				return 'You must specify the heading to use for the modal, i.e., [form modalheading=\'1-Step Approval\']';
			return true;
	}

    /**
     * Configure the form obj settings
     *
     * @param array $atts
     * @since 1.0
     */
	protected function config_form( $atts ) {
		$this->formConfig['prevent'] = array('bootstrap', 'jQuery', 'focus');  // Prevents scripts from loading twice
		switch ( $atts['view'] ) :
			case 'SideBySide' :
				$this->formConfig['view'] = new \PFBC\View\SideBySide;
				break;
			case 'Vertical' :
				$this->formConfig['view'] = new \PFBC\View\Vertical;
				break;
			case 'Inline' :
				$this->formConfig['view'] = new \PFBC\View\Inline;
				break;
			case 'Search' :
				$this->formConfig['view'] = new \PFBC\View\Search;
				break;
			case 'Modal' :
				$this->formConfig['view'] = new \PFBC\View\Modal;
				$this->formConfig['errorView'] = new \PFBC\ErrorView\Modal;
				break;
		endswitch;
		if ( $atts['placeholders'] == 'true' ) :
			$this->formConfig['labelToPlaceholder'] = 1;
		endif;
		if ( $atts['ajax'] == 'true' || $atts['view'] == 'Modal' ) :
			$this->formConfig['action'] = admin_url('admin-ajax.php');
			$this->formConfig['ajax'] = 1;
			$this->formConfig['ajaxCallback'] = 'parseResponse' . $atts['id'];
		else :
			$this->formConfig['action'] = $this->cur_page_url();
		endif;
		if ( $atts['novalidate'] == 'true' ) :
			$this->formConfig['novalidate'] = '';
		endif;
	}

    /**
     * Add a new record from form $_POST
     *
     * @since 1.0
     */
	public function add_record() {
		
		// Add new post
		$title = $this->setTitle();
		$author = $this->setAuthor();
		$new_post = array(  // Create post object
			'post_title'    => trim($title),
			'post_content'  => 'See Custom Fields.',
			'post_type'      => $_POST['web_apper_posttype'],
			'post_status'   => 'publish',
			'post_author'   => $author,
		);
		$postID = wp_insert_post( $new_post );  // insert the post into the database

		// If post was created successfully
		if ( $postID  ) :
		
			$this->add_custom_fields_by_post($postID);
			// Allow form post values to be hooked onto
			if( $_POST['booking-timestamp'] ){
				do_action( 'recordform_post_submit', $postID, $_POST );
			}
			  // Save post meta
			return $this->sendResponse( $_POST['web_apper_success_save'], 'alert-success', 'Hurray!', true );  // Send Response			
		else :  // Else post not created
			return $this->sendResponse( $_POST['web_apper_success_save'], 'alert-error', 'Oh snap!', false );  // Send Response
		endif;
	}
}

$initialize = new RecordForm(); 

?>